# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
import json
from threading import Thread


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "平安学生综合保险"

    # 生成产品信息
    def genProductInfo(self):

        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(6, 19)],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 意外身故/伤残
                "accidentDeath": ["100000"],
                # 住院医疗
                "hospitalMedical": ["0"],
                # 青少年重大疾病
                "teenagerDisease": ["0"],
                # 意外住院医疗
                "accidentHospital": ["60000"],
                # 意外门诊医疗
                "accidentOutpatient": ["5000"],
                # 意外住院津贴
                "accidentAllowance": ["0"],
                # 产品计划
                "plan": ["基础款"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(6, 19)],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 意外身故/伤残
                "accidentDeath": ["100000"],
                # 住院医疗
                "hospitalMedical": ["60000"],
                # 青少年重大疾病
                "teenagerDisease": ["0"],
                # 意外住院医疗
                "accidentHospital": ["60000"],
                # 意外门诊医疗
                "accidentOutpatient": ["5000"],
                # 意外住院津贴
                "accidentAllowance": ["0"],
                # 产品计划
                "plan": ["热销款"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(6, 19)],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 意外身故/伤残
                "accidentDeath": ["100000", "200000", "300000", "400000", "500000"],
                # 住院医疗
                "hospitalMedical": ["0", "60000", "100000"],
                # 青少年重大疾病
                "teenagerDisease": ["0", "50000", "100000", "200000", "300000"],
                # 意外住院医疗
                "accidentHospital": ["0", "20000", "40000", "60000"],
                # 意外门诊医疗
                "accidentOutpatient": ["0", "5000"],
                # 意外住院津贴
                "accidentAllowance": ["0", "100/天"],
                # 产品计划
                "plan": ["自定义"]
            }
        }

        for k in plan:
            for v in product(plan[k]["year"], plan[k]["expire"], plan[k]["payType"], plan[k]["accidentDeath"],
                             plan[k]["hospitalMedical"], plan[k]["teenagerDisease"], plan[k]["accidentHospital"],
                             plan[k]["accidentOutpatient"], plan[k]["accidentAllowance"], plan[k]["plan"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9]
                ))

    # 执行爬虫
    def requestJson(self, dt=None,mysql=None):

        if dt["plan"] == "基础款":

            planCode = "0"
            data = {"planClass": planCode, "amountFormList": [
                {"suddennessDie": 100000, "childrenIll": 0, "hospitalMedic": 60000, "outpatientMedic": 5000,
                 "hospitalAllowance": 0, "vaccineMedic": 0},
                {"suddennessDie": 100000, "childrenIll": 0, "hospitalMedic": 60000, "outpatientMedic": 5000,
                 "hospitalAllowance": 0, "vaccineMedic": 60000},
                {"suddennessDie": "200000", "hospitalMedic": "0", "outpatientMedic": "0", "hospitalAllowance": "100",
                 "vaccineMedic": "100000", "childrenIll": "0"}], "beginDate": "2020-03-17", "insurantNum": "1",
                    "birthDate": "{0}-01-01".format(str(2020 - int(dt["year"])))}

            payload = json.dumps(data)

            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200 and "系统错误，请稍后再试。" not in r.text:
                price = r.json()["quoteResult1"]["originalPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                mysql.updatePrice( data )
            else:
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "state":3
                }
                mysql.updateTask( data )
                print("\n/*产品信息更新失败:%d*/"%dt["id"])

        elif dt["plan"] == "热销款":

            planCode = "1"

            data = {"planClass": planCode, "amountFormList": [
                {"suddennessDie": 100000, "childrenIll": 0, "hospitalMedic": 60000, "outpatientMedic": 5000,
                 "hospitalAllowance": 0, "vaccineMedic": 0},
                {"suddennessDie": 100000, "childrenIll": 0, "hospitalMedic": 60000, "outpatientMedic": 5000,
                 "hospitalAllowance": 0, "vaccineMedic": 60000},
                {"suddennessDie": "200000", "hospitalMedic": "0", "outpatientMedic": "0", "hospitalAllowance": "100",
                 "vaccineMedic": "100000", "childrenIll": "0"}], "beginDate": "2020-03-17", "insurantNum": "1",
                    "birthDate": "{0}-01-01".format(str(2020 - int(dt["year"])))}

            payload = json.dumps(data)

            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200 and "系统错误，请稍后再试。" not in r.text:
                price = r.json()["quoteResult2"]["originalPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                mysql.updatePrice( data )
            else:
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "state":3
                }
                mysql.updateTask( data )
                print("\n/*产品信息更新失败:%d*/"%dt["id"])

        else:
            planCode = "2"

            data = {"planClass": planCode, "amountFormList": [
                {"suddennessDie": 100000, "childrenIll": 0, "hospitalMedic": 60000, "outpatientMedic": 5000,
                 "hospitalAllowance": 0, "vaccineMedic": 0},
                {"suddennessDie": 100000, "childrenIll": 0, "hospitalMedic": 60000, "outpatientMedic": 5000,
                 "hospitalAllowance": 0, "vaccineMedic": 60000},
                {"suddennessDie": dt["accidentDeath"], "hospitalMedic": dt["accidentHospital"], "outpatientMedic": dt["accidentOutpatient"], "hospitalAllowance": "0" if dt["accidentAllowance"] == "0" else "100",
                 "vaccineMedic": dt["hospitalMedical"], "childrenIll": dt["teenagerDisease"]}], "beginDate": "2020-03-17", "insurantNum": "1",
                    "birthDate": "{0}-01-01".format(str(2020 - int(dt["year"])))}

            payload = json.dumps(data)

            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200 and "系统错误，请稍后再试。" not in r.text:
                price = r.json()["quoteResult3"]["originalPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                mysql.updatePrice( data )
            else:
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "state":3
                }
                mysql.updateTask( data )
                print("\n/*产品信息更新失败:%d*/"%dt["id"])

    def main(self,mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)


            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt,mysql)
    # 多线程
    def startProcess(self):

        for i in range(5):
            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()

